<template>
  <div class="activity-dashboard">
    <div class="filter-section">
      <el-radio-group
        v-model="radio"
        @change="onTagChange"
        size="large"
        class="custom-radio-group"
      >
        <el-radio-button value="全部">全部</el-radio-button>
        <el-radio-button value="0">已报名</el-radio-button>
        <el-radio-button value="1">取消报名</el-radio-button>
        <el-radio-button value="2">已签到</el-radio-button>
        <el-radio-button value="3">未签到</el-radio-button>
        <el-radio-button value="4">已参加</el-radio-button>
      </el-radio-group>
    </div>

    <div class="list-content">
      <div
        class="order-item-view"
        v-for="(item, index) in activitySignupData"
        :key="index"
        :class="{
          'status-enrolled': item?.status === 0,
          'status-canceled': item?.status === 1,
          'status-checked-in': item?.status === 2,
          'status-not-checked-in': item?.status === 3,
          'status-participated': item?.status === 4,
        }"
      >
        <div v-if="item != null">
          <div class="header">
            <div class="left">
              <span class="text">活动举办时间</span>
              <span class="time"
                >{{ item.startTime }} 到 {{ item.endTime }}</span
              >
            </div>
            <div class="right">
              <!-- 状态管理按钮 -->
              <div class="action-buttons">
                <!-- 已报名状态下可以取消报名 -->
                <el-button
                  v-if="item.status === 0"
                  type="danger"
                  size="default"
                  :icon="Delete"
                  class="action-button"
                  @click="cancelActivitySignup(item)"
                >
                  取消报名
                </el-button>

                <!-- 取消报名状态下可以重新报名 -->
                <el-button
                  v-if="item.status === 1"
                  type="primary"
                  size="default"
                  :icon="Check"
                  class="action-button"
                  @click="activitySignup(item)"
                >
                  报名
                </el-button>

                <!-- 已报名但未签到，可以签到 -->
                <el-button
                  v-if="item.status === 3 && isEventInProgress(item)"
                  type="success"
                  size="default"
                  :icon="Calendar"
                  class="action-button"
                  @click="checkInActivity(item)"
                >
                  签到
                </el-button>

                <!-- 展示状态标签 -->
                <div class="status-badge" :class="'status-' + item.status">
                  {{ activityStatusMap[item.status] || "未知状态" }}
                </div>
              </div>
            </div>
          </div>

          <div class="content">
            <div class="left-list">
              <div class="list-item">
                <img :src="item.cover" class="activity-img" alt="活动封面" />
                <div class="detail">
                  <div class="activity-info">
                    <div class="info-row">
                      <span class="label">活动名称</span>
                      <h2 class="value title-value">{{ item.title }}</h2>
                    </div>
                    <div class="info-row category-row">
                      <span class="label">活动分类</span>
                      <span class="value category-tag">{{
                        item.categoryName
                      }}</span>
                    </div>
                    <div class="info-row description-row">
                      <span class="label">活动描述</span>
                      <p class="value">{{ item.description }}</p>
                    </div>
                    <div class="additional-info-row">
                      <div class="participant-info">
                        <span class="label">报名人数</span>
                        <span class="value participants-count">
                          <i class="el-icon-user-solid"></i>
                          {{ item.amount }}
                        </span>
                      </div>

                      <!-- 活动进度条 -->
                      <div class="event-progress" v-if="item.status !== 2">
                        <span class="label">活动进度</span>
                        <el-progress
                          :percentage="calculateProgress(item)"
                          :status="getProgressStatus(item)"
                          :stroke-width="10"
                          :show-text="false"
                        ></el-progress>
                        <span class="progress-text">{{
                          getProgressText(item)
                        }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="right-info">
              <div class="organizer-section">
                <div class="organizer-avatar">
                  <el-avatar :icon="User" :size="50"></el-avatar>
                </div>
                <div class="organizer-info">
                  <h3>主办人信息</h3>
                  <p class="info-item">
                    <el-icon><User /></el-icon> {{ item.holdName }}
                  </p>
                  <p class="info-item">
                    <el-icon><Phone /></el-icon> {{ item.holdPhone }}
                  </p>
                </div>
              </div>

              <div class="location-section">
                <h3>
                  <el-icon><Location /></el-icon> 活动地址
                </h3>
                <p>{{ item.detailAddress }}</p>
              </div>

              <div class="remarks-section">
                <h3>
                  <el-icon><Document /></el-icon> 备注信息
                </h3>
                <p>{{ item.remark || "暂无备注" }}</p>
              </div>
            </div>
          </div>

          <div class="bottom">
            <div class="left">
              <div class="activity-date">
                <el-icon><Calendar /></el-icon>
                <span>报名时间: {{ item.signupTime }}</span>
              </div>
            </div>
            <div class="right">
              <span class="participants">
                <el-icon><User /></el-icon> 共
                <span class="highlight">{{ item.amount }}</span> 人参与
              </span>
              <el-button
                type="primary"
                text
                class="details-button"
                @click="navigateToActivity(item.activityId)"
              >
                活动详情
                <el-icon class="el-icon--right"><ArrowRight /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <el-empty
        v-if="activitySignupData.length === 0"
        description="暂无活动数据"
      ></el-empty>

      <div class="pagination">
        <el-pagination
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          :default-page-size="pagination.size"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          background
        />
      </div>
    </div>

    <el-dialog
      v-model="checkInDialogVisible"
      title="活动签到"
      width="400px"
      center
      @close="closeCheckInDialog"
    >
      <el-form
        ref="checkInForm"
        :model="{ checkInCode }"
        :rules="checkInRules"
        label-position="top"
      >
        <el-form-item label="请输入签到码" prop="checkInCode">
          <el-input
            v-model="checkInCode"
            placeholder="请输入活动签到码"
            maxlength="6"
            show-word-limit
            clearable
            autofocus
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-tip">
        <el-icon><InfoFilled /></el-icon>
        <span>签到码由活动组织者提供，请向活动主办方获取</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeCheckInDialog">取 消</el-button>
          <el-button type="primary" @click="submitCheckIn" :loading="false">
            确认签到
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Delete,
  Check,
  User,
  Phone,
  Location,
  Document,
  ArrowRight,
  Calendar,
  Lock,
  InfoFilled,
} from "@element-plus/icons-vue";
import {
  activitySignupPage,
  activitySignupEdit,
  validateCheckInCode,
} from "@/apis/user/activity-signup";

const router = useRouter();

// 存储活动数据
const activitySignupData = ref([]);

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0,
});

// 状态： 1-已报名 2-取消报名 3-已签到 4-未签到 5-已参加
const activityStatusMap = {
  0: "已报名",
  1: "取消报名",
  2: "已签到",
  3: "未签到",
  4: "已参加",
};

// 搜索输入框搜索条件
const search = reactive({
  id: "",
  status: "",
  activityId: "",
  remark: "",
  title: "",
  cover: "",
});

// 过滤对应的条件
const filter = ref({});

// 存储排序字段
const orders = reactive({});

// 选择的状态标签
const radio = ref("全部");

// 获取数据
const getActivitySignupPage = async () => {
  try {
    const result = await activitySignupPage(
      {
        filter: filter.value,
        search: search,
        orders: [orders],
      },
      pagination.page,
      pagination.size
    );

    activitySignupData.value = result.data.records;
    pagination.total = result.data.total;
  } catch (error) {
    ElMessage.error("获取活动数据失败");
    console.error(error);
  }
};

// 检查活动是否正在进行中
const isEventInProgress = (item) => {
  const now = new Date();
  const startTime = new Date(item.startTime);
  const endTime = new Date(item.endTime);
  return now >= startTime && now <= endTime;
};

// 检查活动是否已结束
const isEventEnded = (item) => {
  const now = new Date();
  const endTime = new Date(item.endTime);
  return now > endTime;
};

// 计算活动进度百分比
const calculateProgress = (item) => {
  const now = new Date();
  const startTime = new Date(item.startTime);
  const endTime = new Date(item.endTime);

  if (now < startTime) return 0;
  if (now > endTime) return 100;

  const totalDuration = endTime - startTime;
  const elapsedDuration = now - startTime;
  return Math.round((elapsedDuration / totalDuration) * 100);
};

// 获取进度条状态
const getProgressStatus = (item) => {
  if (isEventEnded(item)) return "success";
  if (isEventInProgress(item)) return "";
  return "warning";
};

// 获取进度文字
const getProgressText = (item) => {
  if (isEventEnded(item)) return "活动已结束";
  if (isEventInProgress(item)) return "活动进行中";
  return "即将开始";
};

// 实现跳转活动详情页,传递路径参数
const navigateToActivity = (activityId) => {
  router.push({
    name: "activityDetail",
    params: { activityId: activityId },
  });
};

// 点击标签页的触发函数
const onTagChange = (key) => {
  if (key !== "全部") {
    search.status = key;
  } else {
    search.status = "";
  }
  pagination.page = 1; // 切换标签时重置页码
  getActivitySignupPage();
};

// 取消报名
const cancelActivitySignup = async (item) => {
  try {
    ElMessageBox.confirm("确定要取消此活动报名吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      const newActivitySignup = reactive({});
      Object.assign(newActivitySignup, item);
      newActivitySignup.status = 1; // 更改为取消报名状态

      await activitySignupEdit(newActivitySignup);
      ElMessage.success("已成功取消报名");
      getActivitySignupPage();
    });
  } catch (error) {
    ElMessage.error("取消报名失败");
    console.error(error);
  }
};

// 报名活动
const activitySignup = async (item) => {
  const newActivitySignup = reactive({});
  Object.assign(newActivitySignup, item);
  confirmActivitySignup(newActivitySignup);
};

// 确认活动报名消息
const confirmActivitySignup = (item) => {
  ElMessageBox.confirm("确定要报名此活动吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "info",
    showClose: true,
  })
    .then(async () => {
      try {
        item.status = 0; // 更改为已报名状态
        await activitySignupEdit(item);
        ElMessage({
          type: "success",
          message: "活动报名成功",
        });
        getActivitySignupPage();
      } catch (error) {
        ElMessage.error("报名失败");
        console.error(error);
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消操作",
      });
    });
};

// 活动签到
const checkInActivity = (item) => {
  currentCheckInItem.value = item;
  checkInCode.value = ""; // 清空之前的签到码
  checkInDialogVisible.value = true;
};

// 分页相关方法
const handleCurrentChange = (val) => {
  pagination.page = val;
  getActivitySignupPage();
};

const handleSizeChange = (val) => {
  pagination.size = val;
  pagination.page = 1;
  getActivitySignupPage();
};

// 页面加载时执行
onMounted(() => {
  getActivitySignupPage();
});

// 添加签到码表单相关变量
const checkInDialogVisible = ref(false);
const checkInCode = ref("");
const checkInForm = ref(null);
const currentCheckInItem = ref(null);
const checkInRules = {
  checkInCode: [
    { required: true, message: "请输入签到码", trigger: "blur" },
    { min: 6, max: 6, message: "签到码长度为6位", trigger: "blur" },
  ],
};

// 提交签到码验证
const submitCheckIn = async () => {
  if (!checkInForm.value) return;

  await checkInForm.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = {
          captcha: checkInCode.value,
          id: currentCheckInItem.value.activityId,
        };
        console.log(data);
        
        // 验证签到码
        const isValid = await validateCheckInCode(data);

        if (isValid) {
          const newActivitySignup = reactive({});
          Object.assign(newActivitySignup, currentCheckInItem.value);
          // 更改为已签到状态
          newActivitySignup.status = 2;

          await activitySignupEdit(newActivitySignup);
          ElMessage.success("签到成功！");
          checkInDialogVisible.value = false;
          getActivitySignupPage();
        } else {
          ElMessage.error("签到码错误，请重新输入");
        }
      } catch (error) {
        ElMessage.error("签到失败");
        console.error(error);
      }
    } else {
      ElMessage.warning("请输入有效的签到码");
      return false;
    }
  });
};

// // 验证签到码的方法
// const validateCheckInCode = async (code, activityId) => {
//   // 这里应该是一个API调用，用于验证签到码是否正确
//   // 例如：return await checkActivityCode(code, activityId);

//   // 示例验证逻辑：临时使用简单验证，实际项目中应该通过API调用
//   console.log(`验证活动 ${activityId} 的签到码: ${code}`);

//   // 模拟异步操作
//   return new Promise((resolve) => {
//     setTimeout(() => {
//       // 示例：验证码为"1234"或活动ID后四位才有效
//       const validCode = "1234";
//       const activityIdStr = String(activityId);
//       const idLastFour = activityIdStr.substring(
//         Math.max(0, activityIdStr.length - 4)
//       );

//       resolve(code === validCode || code === idLastFour);
//     }, 600);
//   });
// };

// 关闭签到对话框
const closeCheckInDialog = () => {
  checkInDialogVisible.value = false;
  checkInCode.value = "";
};
</script>

<style lang="less" scoped>
.activity-dashboard {
  font-family: "PingFang SC", "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.filter-section {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

  .custom-radio-group {
    width: 100%;
    display: flex;
    justify-content: space-around;

    :deep(.el-radio-button__inner) {
      padding: 10px 24px;
      font-weight: 500;
    }

    :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
      background-color: #3b82f6;
      color: white;
      border-color: #3b82f6;
      box-shadow: 0 3px 8px rgba(59, 130, 246, 0.3);
    }
  }
}

.list-content {
  background-color: #f7f9fe;
  padding: 20px;
  border-radius: 12px;
}

.order-item-view {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
  padding: 28px;
  margin-bottom: 28px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.09);
  }

  &.status-enrolled {
    border-left: 5px solid #3b82f6;
  }

  &.status-canceled {
    border-left: 5px solid #ef4444;
  }

  &.status-checked-in {
    border-left: 5px solid #10b981;
  }

  &.status-not-checked-in {
    border-left: 5px solid #f59e0b;
  }

  &.status-participated {
    border-left: 5px solid #8b5cf6;
  }
}

/* 顶部区域 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 22px;
  padding-bottom: 18px;
  border-bottom: 1px dashed #e5e7eb;

  .left {
    .text {
      color: #6b7280;
      margin-right: 10px;
      font-size: 14px;
    }

    .time {
      color: #1f2937;
      font-weight: 600;
      font-size: 16px;
    }
  }

  .right {
    display: flex;
    align-items: center;
    gap: 16px;

    .action-buttons {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .action-button {
      border-radius: 8px;
      font-weight: 600;
      padding: 8px 16px;
      transition: all 0.2s;

      &:hover {
        transform: translateY(-2px);
      }
    }

    .status-badge {
      padding: 6px 14px;
      border-radius: 20px;
      font-size: 14px;
      font-weight: 600;
      color: white;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);

      &.status-0 {
        background: linear-gradient(135deg, #3b82f6, #2563eb);
      }

      &.status-1 {
        background: linear-gradient(135deg, #ef4444, #dc2626);
      }

      &.status-2 {
        background: linear-gradient(135deg, #10b981, #059669);
      }

      &.status-3 {
        background: linear-gradient(135deg, #f59e0b, #d97706);
      }

      &.status-4 {
        background: linear-gradient(135deg, #8b5cf6, #7c3aed);
      }
    }
  }
}

/* 中间区域 */
.content {
  display: flex;
  gap: 28px;
  margin-bottom: 22px;

  @media (max-width: 768px) {
    flex-direction: column;
  }
}

.left-list {
  flex: 2;
}

.right-info {
  flex: 1;
  background: linear-gradient(to bottom, #f9fafc, #f1f4f9);
  padding: 24px;
  border-radius: 14px;
  position: relative;
  box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.03);

  h3 {
    font-size: 16px;
    color: #374151;
    margin-bottom: 14px;
    display: flex;
    align-items: center;
    gap: 8px;

    .el-icon {
      color: #3b82f6;
    }
  }

  .organizer-section,
  .location-section,
  .remarks-section {
    margin-bottom: 22px;
    padding-bottom: 18px;
    border-bottom: 1px dashed #e5e7eb;

    &:last-child {
      border-bottom: none;
      margin-bottom: 0;
      padding-bottom: 0;
    }
  }

  .organizer-section {
    display: flex;
    gap: 16px;

    .organizer-avatar {
      flex-shrink: 0;
    }

    .organizer-info {
      flex: 1;

      h3 {
        margin-bottom: 10px;
      }

      .info-item {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;
        color: #4b5563;

        .el-icon {
          color: #3b82f6;
          font-size: 16px;
        }
      }
    }
  }
}

/* 活动内容卡片 */
.list-item {
  display: flex;
  gap: 22px;

  @media (max-width: 576px) {
    flex-direction: column;
  }
}

.activity-img {
  width: 180px;
  height: 140px;
  object-fit: cover;
  border-radius: 12px;
  flex-shrink: 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &:hover {
    transform: scale(1.03);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  }

  @media (max-width: 576px) {
    width: 100%;
    height: 200px;
    margin-bottom: 18px;
  }
}

.detail {
  flex: 1;
}

.activity-info {
  .info-row {
    margin-bottom: 14px;

    .label {
      display: block;
      font-size: 13px;
      color: #6b7280;
      margin-bottom: 5px;
    }

    .value {
      color: #374151;
      font-weight: 500;

      &.title-value {
        font-size: 20px;
        font-weight: 700;
        margin-bottom: 14px;
        color: #111827;
        line-height: 1.3;
      }
    }

    &.category-row {
      margin-bottom: 16px;
    }

    .category-tag {
      display: inline-block;
      background: #ebf5ff;
      color: #3b82f6;
      padding: 6px 12px;
      border-radius: 20px;
      font-size: 14px;
      font-weight: 600;
      box-shadow: 0 1px 2px rgba(59, 130, 246, 0.1);
    }

    &.description-row {
      .value {
        line-height: 1.7;
        max-height: 85px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
        color: #4b5563;
      }
    }
  }

  .additional-info-row {
    display: flex;
    align-items: center;
    gap: 32px;
    margin-top: 18px;

    .participant-info {
      .label {
        font-size: 13px;
        color: #6b7280;
        margin-bottom: 5px;
        display: block;
      }

      .participants-count {
        font-weight: 700;
        color: #3b82f6;
        font-size: 16px;
        display: flex;
        align-items: center;
        gap: 6px;

        .el-icon {
          margin-right: 4px;
        }
      }
    }

    .event-progress {
      flex: 1;

      .label {
        font-size: 13px;
        color: #6b7280;
        margin-bottom: 5px;
        display: block;
      }

      .progress-text {
        font-size: 12px;
        color: #6b7280;
        margin-top: 4px;
        display: block;
        text-align: right;
      }
    }

    @media (max-width: 576px) {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;

      .event-progress {
        width: 100%;
      }
    }
  }
}

/* 底部区域 */
.bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px dashed #e5e7eb;
  padding-top: 18px;
  margin-top: 10px;

  .left {
    .activity-date {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #6b7280;
      font-size: 14px;

      .el-icon {
        color: #3b82f6;
      }
    }
  }

  .right {
    display: flex;
    align-items: center;
    gap: 24px;

    .participants {
      color: #4b5563;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 6px;

      .el-icon {
        color: #3b82f6;
      }

      .highlight {
        font-weight: 700;
        color: #3b82f6;
      }
    }

    .details-button {
      font-weight: 600;
      color: #3b82f6;
      transition: all 0.2s;
      display: flex;
      align-items: center;

      &:hover {
        transform: translateX(3px);
      }

      .el-icon {
        margin-left: 6px;
        transition: all 0.2s;
      }

      &:hover .el-icon {
        transform: translateX(3px);
      }
    }
  }
}

/* 分页 */
.pagination {
  margin-top: 40px;
  text-align: center;

  :deep(.el-pagination) {
    justify-content: center;
  }
}

// 响应式调整
@media (max-width: 992px) {
  .content {
    flex-direction: column;
  }

  .right-info {
    margin-top: 20px;
  }

  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;

    .right {
      width: 100%;
      justify-content: space-between;
    }
  }

  .bottom {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;

    .right {
      width: 100%;
      justify-content: space-between;
    }
  }
}

.dialog-tip {
  background-color: #f0f9ff;
  border-left: 4px solid #3b82f6;
  padding: 12px 16px;
  margin: 16px 0;
  border-radius: 6px;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
  color: #4b5563;

  .el-icon {
    color: #3b82f6;
    font-size: 16px;
    flex-shrink: 0;
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
  margin-top: 10px;
  gap: 16px;
}
</style>
